<template>
  <div class="dish-container">
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增菜品
      </el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索菜品名称"
        prefix-icon="Search"
        clearable
        style="width: 300px; margin-left: 20px"
        @input="handleSearch"
      />
    </div>

    <el-table :data="sortedDishList" style="width: 100%" border stripe highlight-current-row>
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" sortable />
      <el-table-column label="图片" width="100">
        <template #default="scope">
          <el-image
            v-if="scope.row.image"
            :src="scope.row.image"
            :preview-src-list="[scope.row.image]"
            fit="cover"
            style="width: 60px; height: 60px; border-radius: 4px;"
          />
          <div v-else class="no-image">
            <el-icon><Picture /></el-icon>
            <span>暂无图片</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="菜品名称" width="150" />
      <el-table-column prop="price" label="价格" width="100">
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑菜品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增菜品' : '编辑菜品'"
      width="600px"
    >
      <el-form :model="dishForm" :rules="rules" ref="dishFormRef" label-width="100px">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="dishForm.name" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="菜品价格" prop="price">
          <el-input-number v-model="dishForm.price" :min="0" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="菜品图片" prop="image">
          <el-upload
            class="dish-image-uploader"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :http-request="handleImageUpload"
            accept="image/*"
          >
            <el-image
              v-if="dishForm.image"
              :src="dishForm.image"
              class="dish-image"
              fit="cover"
            />
            <el-icon v-else class="dish-image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            <p>支持 jpg、png、gif 格式，文件大小不超过 2MB</p>
            <el-button v-if="dishForm.image" type="danger" size="small" @click="removeImage">删除图片</el-button>
          </div>
        </el-form-item>
        <el-form-item label="菜品描述" prop="description">
          <el-input
            v-model="dishForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入菜品描述"
          />
        </el-form-item>
        <el-form-item label="菜品状态" prop="status">
          <el-switch v-model="dishForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Plus, Picture } from '@element-plus/icons-vue'
import axios from 'axios'

// 配置axios
axios.defaults.baseURL = 'http://localhost:8080'
axios.defaults.timeout = 10000

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 可以在这里添加token等认证信息
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  response => {
    // 打印响应数据，帮助调试
    console.log('API响应数据:', response.data)
    return response
  },
  error => {
    console.error('API请求错误:', error)
    ElMessage.error('请求失败，请检查网络连接')
    return Promise.reject(error)
  }
)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)  // 初始化为0，避免显示不准确

// 搜索关键词
const searchKeyword = ref('')

// 默认菜品数据（当API调用失败时使用，按ID升序排列）
const defaultDishes = [
  {
    id: 1,
    name: '回锅肉',
    description: '传统川菜，肥而不腻',
    price: 38,
    image: 'https://images.unsplash.com/photo-1565299624946-b28f40a0ca4b?w=400&h=300&fit=crop',
    status: 1
  },
  {
    id: 2,
    name: '鱼香肉丝',
    description: '经典川菜，口味独特',
    price: 32,
    image: 'https://images.unsplash.com/photo-1512058564366-18510be2db19?w=400&h=300&fit=crop',
    status: 1
  },
  {
    id: 3,
    name: '宫保鸡丁',
    description: '酥脆可口，香辣适中',
    price: 36,
    image: 'https://images.unsplash.com/photo-1559847844-d721426d6edc?w=400&h=300&fit=crop',
    status: 1
  }
]

// 菜品列表
const dishList = ref([...defaultDishes])

// 按ID升序排序的菜品列表
const sortedDishList = computed(() => {
  const sorted = [...dishList.value].sort((a, b) => a.id - b.id)
  console.log('排序后的菜品列表:', sorted)
  return sorted
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const dishFormRef = ref<FormInstance>()
const dishForm = reactive({
  id: 0,
  name: '',
  price: 0,
  description: '',
  image: '',
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入菜品名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入菜品价格', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入菜品描述', trigger: 'blur' }
  ]
}

// 从后端获取菜品数据
const fetchDishList = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 调用后端API获取菜品列表
    const response = await axios.get('/dish/page', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        name: searchKeyword.value
      }
    })

    if (response.data.code === 1) {
      // 获取后端返回的菜品数据
      const records = response.data.data.records || []

      // 更新菜品列表和总数
      dishList.value = records
      total.value = response.data.data.total || records.length

      // 如果后端没有返回总数，但有返回记录，则使用记录数量作为总数
      if (total.value === 0 && records.length > 0) {
        total.value = records.length
      }

      console.log('从后端获取的菜品列表数据:', records)
      console.log('总记录数:', total.value)
    } else {
      ElMessage.error(response.data.msg || '获取菜品列表失败')
    }
  } catch (error) {
    console.error('获取菜品列表出错:', error)
    ElMessage.error('获取菜品列表失败，使用默认数据')

    // 出错时，使用默认菜品数据
    if (dishList.value.length === 0) {
      dishList.value = [...defaultDishes]
    }

    // 确保总数至少等于当前显示的菜品数量
    total.value = dishList.value.length
  } finally {
    loading.close()
  }
}

// 搜索菜品
const handleSearch = () => {
  currentPage.value = 1
  fetchDishList()
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchDishList()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchDishList()
}

// 新增菜品
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑菜品
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  resetForm()
  Object.assign(dishForm, row)
  dialogVisible.value = true
}

// 删除菜品
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除菜品"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '删除中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      // 调用后端API删除菜品
      const response = await axios.delete('/dish', {
        params: {
          ids: row.id.toString()  // 修改为字符串，避免方括号编码问题
        }
      })

      if (response.data.code === 1) {
        ElMessage.success('删除成功')
        fetchDishList() // 重新加载菜品列表
      } else {
        ElMessage.error(response.data.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除菜品出错:', error)
      ElMessage.error('删除失败，请稍后再试')
    } finally {
      loading.close()
    }
  }).catch(() => {})
}

// 修改菜品状态
const handleStatusChange = async (row: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '更新中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 调用后端API修改菜品状态
    const response = await axios.post(`/dish/status/${row.status}`, null, {
      params: {
        ids: row.id.toString()  // 修改为字符串，避免方括号编码问题
      }
    })

    if (response.data.code === 1) {
      const statusText = row.status === 1 ? '启用' : '停用'
      ElMessage.success(`${row.name}已${statusText}`)
    } else {
      // 如果失败，恢复原状态
      row.status = row.status === 1 ? 0 : 1
      ElMessage.error(response.data.msg || '状态修改失败')
    }
  } catch (error) {
    // 如果出错，恢复原状态
    row.status = row.status === 1 ? 0 : 1
    console.error('修改菜品状态出错:', error)
    ElMessage.error('状态修改失败，请稍后再试')
  } finally {
    loading.close()
  }
}

// 图片上传前的验证
const beforeImageUpload = (file: File) => {
  const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isValidType) {
    ElMessage.error('只能上传 JPG、PNG、GIF 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义图片上传
const handleImageUpload = (options: any) => {
  const file = options.file

  // 创建 FileReader 来读取文件
  const reader = new FileReader()
  reader.onload = (e) => {
    // 获取base64数据
    const base64Data = e.target?.result as string

    // 压缩图片
    const img = new Image()
    img.onload = () => {
      // 创建canvas
      const canvas = document.createElement('canvas')
      // 设置最大宽度和高度
      const MAX_WIDTH = 800
      const MAX_HEIGHT = 600
      let width = img.width
      let height = img.height

      // 调整尺寸
      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width
          width = MAX_WIDTH
        }
      } else {
        if (height > MAX_HEIGHT) {
          width *= MAX_HEIGHT / height
          height = MAX_HEIGHT
        }
      }

      canvas.width = width
      canvas.height = height

      // 绘制图片
      const ctx = canvas.getContext('2d')
      ctx?.drawImage(img, 0, 0, width, height)

      // 转换为base64，使用较低的质量
      const compressedBase64 = canvas.toDataURL('image/jpeg', 0.7)

      // 更新表单
      dishForm.image = compressedBase64
      ElMessage.success('图片上传成功')
    }

    img.src = base64Data
  }
  reader.readAsDataURL(file)
}

// 删除图片
const removeImage = () => {
  dishForm.image = ''
  ElMessage.success('图片已删除')
}

// 重置表单
const resetForm = () => {
  if (dishFormRef.value) {
    dishFormRef.value.resetFields()
  }
  dishForm.id = 0
  dishForm.name = ''
  dishForm.price = 0
  dishForm.description = ''
  dishForm.image = ''
  dishForm.status = 1
}

// 提交表单
const submitForm = async () => {
  if (!dishFormRef.value) return

  await dishFormRef.value.validate(async (valid) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: '提交中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        if (dialogType.value === 'add') {
          // 新增菜品
          const response = await axios.post('/dish', {
            name: dishForm.name,
            price: dishForm.price,
            description: dishForm.description,
            image: dishForm.image,
            status: dishForm.status,
            merchantId: 1 // 假设当前商家ID为1
          })

          if (response.data.code === 1) {
            ElMessage.success('新增成功')
            fetchDishList() // 重新加载菜品列表
          } else {
            ElMessage.error(response.data.msg || '新增失败')
          }
        } else {
          // 编辑菜品
          const response = await axios.put('/dish', {
            id: dishForm.id,
            name: dishForm.name,
            price: dishForm.price,
            description: dishForm.description,
            image: dishForm.image,
            status: dishForm.status
          })

          if (response.data.code === 1) {
            ElMessage.success('编辑成功')
            fetchDishList() // 重新加载菜品列表
          } else {
            ElMessage.error(response.data.msg || '编辑失败')
          }
        }
        dialogVisible.value = false
      } catch (error) {
        console.error('提交菜品数据出错:', error)
        ElMessage.error('操作失败，请稍后再试')
      } finally {
        loading.close()
      }
    }
  })
}

// 组件挂载时加载数据
onMounted(() => {
  // 确保初始化时总数至少等于当前显示的菜品数量
  if (total.value === 0 && dishList.value.length > 0) {
    total.value = dishList.value.length
  }

  // 从后端获取菜品数据
  fetchDishList()
})
</script>

<style scoped>
.dish-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 12px;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  background-color: #f5f7fa;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  color: #c0c4cc;
  font-size: 12px;
}

.no-image .el-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.dish-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.dish-image-uploader:hover {
  border-color: #409eff;
}

.dish-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.dish-image {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-tip {
  margin-top: 10px;
}

.upload-tip p {
  margin: 0 0 10px 0;
  color: #999;
  font-size: 12px;
}
</style>
